package com.example.springbootgraduation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootgraduation.entity.Menu;
import com.example.springbootgraduation.entity.Role;
import com.example.springbootgraduation.service.MenuService;
import com.example.springbootgraduation.service.RoleService;
import com.example.springbootgraduation.utils.TreeNode;
import com.example.springbootgraduation.vo.DataView;
import com.example.springbootgraduation.vo.RoleVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//角色
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private MenuService menuService;

    /**
     * 跳转页面
     */
    @RequestMapping("/toRole")
    public String toRole(){
        return "role/role";
    }

    /**
     * 查询所有的角色，带有分页
     */
    @RequestMapping("/loadAllRole")
    @ResponseBody
    public DataView loadAllRole(RoleVo roleVo){
        IPage<Role> page = new Page<>(roleVo.getPage(),roleVo.getLimit());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        //1、判断前端传过来的不能为空，2、数据库列的名字，3、获得将当前传过来的值
        queryWrapper.like(StringUtils.isNoneBlank(roleVo.getName()),"name",roleVo.getName());
        queryWrapper.like(StringUtils.isNoneBlank(roleVo.getRemark()),"remark",roleVo.getRemark());
        roleService.page(page,queryWrapper);//查数据
        return new DataView(page.getTotal(),page.getRecords());
    }

    /**
     *添加角色
     */
    @RequestMapping("/addRole")
    @ResponseBody
    public DataView addRole(Role role){
        roleService.save(role);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("添加角色成功！");
        return dataView;
    }

    /**
     *删除角色
     */
    @RequestMapping("/deleteRole")
    @ResponseBody
    public DataView deleteRole(Role role){
        roleService.removeById(role.getId());
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("删除角色成功！");
        return dataView;
    }

    /**
     * 修改角色
     */
    @RequestMapping("/updateRole")
    @ResponseBody DataView updateRole(Role role){
        roleService.saveOrUpdate(role);
        DataView dataView = new DataView();
        dataView.setCode(200);
        dataView.setMsg("修改角色成功！");
        return dataView;
    }

    /**
     * 初始化下拉列表的权限
     * 根据角色查询菜单
     * select **mid** from role_meun where rid=?
     */
    @RequestMapping("/initPermissionByRoleId")
    @ResponseBody
    public DataView initPermissionByRoleId(Integer roleId){//前台返回一个Integer类型
//        1.把所有的菜单权限查出来
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        List<Menu> allPermissions = menuService.list();//查到所有菜单
//        2.根据角色rid[roleId]查询所有的菜单mid
        List<Integer> currentRolePermissions =  roleService.queryAllPermissionByRid(roleId);
//        3.rid mid 所有的ID,去查询菜单和角色的数据
        List<Menu> menus = null;
//        4.查询到 mid rid
        if (currentRolePermissions.size()>0){
            queryWrapper.in("id",currentRolePermissions);//查到id,将currentRolePermissions放进去
            menus = menuService.list(queryWrapper);//给menus赋值
        }else {
            menus = new ArrayList<>();//空的集合
        }
//        5.返回前台的格式,带有层级关系 TREENODE
        List<TreeNode> nodes = new ArrayList<>();
//        拿到的数据放进TreeNode
        for (Menu allPermission : allPermissions){//拿到allPermissions
            String checkArr = "0";
            for (Menu currentPermission : menus){
                if (allPermission.getId().equals(currentPermission.getId())){
                    checkArr = "1";//展开还是不展开
                    break;
                }
            }
            Boolean spread = (allPermission.getOpen()==null || allPermission.getOpen() == 1) ?true:false;//等于1默认展开否则不展开
//            6.放进节点
            nodes.add(new TreeNode(allPermission.getId(),allPermission.getPid(),allPermission.getTitle(),spread,checkArr));
        }
        return new DataView(nodes);
    }

    /**
     * 点击确认分配权限
     * 插入数据表[role_menu]
     * var params = "rid="+data.id;
     * console.log(params);
     *  $.each(permissionData,function (index, item) {
     params+="&ids="+item.nodeId;
     });
     */
    @RequestMapping("/saveRolePermission")
    @ResponseBody
    public  DataView saveRolePermission(Integer rid,Integer[] mids){
//        1.根据rid删除之前的mid权限
        roleService.deleteRoleByRid(rid);//直接删除不给返回值
//        2.保存权限
        if (mids!=null && mids.length>0){
            for (Integer mid : mids){
                roleService.saveRoleMenu(rid,mid);
            }
        }
        DataView dataView = new DataView();
        dataView.setMsg("菜单权限分配成功!");
        dataView.setCode(200);
        return dataView;
    }
}
